var path = require('path');
var { pool, model } = require(path.join(__dirname, '..', 'help', 'mysql.js'));
var conf = require(path.join(__dirname, '..', 'help', 'conf.js'));
var timemachine = require(path.join(__dirname, '..', 'help', 'timemachine.js'));
var redis = require(path.join(__dirname, '..', 'help', 'redis.js'));
const Redlock = require('redlock');
const redlock = new Redlock([redis], {
    retryDelay: 200, // time in ms
    retryCount: 5,
});

//https://www.php.cn/redis/487848.html
//https://blog.csdn.net/dj1540225203/article/details/122090220
//https://zhuanlan.zhihu.com/p/93460690
//https://lequ7.com/guan-yu-nodejsnodejs-ji-yu-redis-de-fen-bu-shi-suo-de-shi-xian-redlock-suan-fa.html
//https://www.jianshu.com/p/21b488c1ede5



/*

--
-- 表的结构 `lock_test`
--

CREATE TABLE `lock_test` (
  `id` int(10) UNSIGNED NOT NULL,
  `username` varchar(100) NOT NULL,
  `addtime` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- 转储表的索引
--

--
-- 表的索引 `lock_test`
--
ALTER TABLE `lock_test`
  ADD PRIMARY KEY (`id`);

--
-- 在导出的表使用AUTO_INCREMENT
--

--
-- 使用表AUTO_INCREMENT `lock_test`
--
ALTER TABLE `lock_test`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
COMMIT;

*/
//https://www.npmjs.com/package/node-redis-warlock
//https://www.npmjs.com/package/redis-lock
//https://www.npmjs.com/package/redlock/v/4.2.0
//npm i redlock@4.2.0

async function op(username) {
    for (let i = 0; i < 50; i++) {
        try {
            //加锁
            const lock = await redlock.lock(username, 3000);
            let is_exist = await model.value('select id from lock_test where username=?', [username]);
            console.log(username, 'is_exist', is_exist > 0);
            if (is_exist > 0) {
                //解锁
                lock.unlock();
                continue;
            }
            await model.i('insert into lock_test set ?', {
                username: username,
                addtime: timemachine.time(),
            });
            //解锁
            lock.unlock();
        } catch (err) {
            console.log(err);
        }

    }
    console.log('op:', username);
    return true;
}

async function start() {

    //张三的报名
    setImmediate(async () => {
        await op('张三');
    });
    //张三的报名
    setImmediate(async () => {
        await op('张三');
    });
    //李四的报名
    setImmediate(async () => {
        await op('李四');
    });
    //李四的报名
    setImmediate(async () => {
        await op('李四');
    });

    //王五的报名
    setImmediate(async () => {
        await op('王五');
    });
    //王五的报名
    setImmediate(async () => {
        await op('王五');
    });

    setTimeout(() => {
        console.log('进程退出');
        process.exit();
    }, 10000);
}

start();